/**
 
 This file is part of clibudget - a tool to manage your budgets from the
 command-line.

 Function definitions for clibudget

 Copyright 2022 - kzimmermann 

 This program is Free Software licensed under the terms and conditions of the
 GNU GPL v3. For more information, see https://www.gnu.org/licenses

*/

#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "functions.h"

int
make_config(char* filename)
{
    // open file for writing
    FILE* cfg = fopen(filename, "w");

    if (cfg == NULL) {
        printf("Error: could not make config file.\n");
        printf("Make sure you have permissions to write it.\n");
        return 1;
    }

    // let's print some meta-documentation:
    fprintf(cfg, "# Configuration file for clibudget\n");
    fprintf(cfg, "# Options are defined in key=value lines, no spaces between '=' character.\n");
    fprintf(cfg, "# Lines starting with '#' are ignored.\n");

    fprintf(cfg, "categories=Bills,Meals,Food and Supplies,Medical,Transportation,Other\n");
    fprintf(cfg, "debug=true\n");

    fclose(cfg);
    return 0;
}

int
read_config(char* filename)
{
    FILE* cfg = fopen(filename, "r");

    if (cfg == NULL) {
        printf("Error: could not read config file %s\n", filename);
        printf("Make sure the file exists and try again\n");
        return 1;
    }

    // This is how you properly read a file line by line in C...
    char line[250];
    //char sep = '=';
    while (fgets(line, sizeof(line), cfg) != NULL) {
        char key[250];
        char value[250];

        // ignore Unix-like comments
        if (line[0] == '#')
            continue;

        sscanf(line, "%[^=]=%[^\n]", key, value);
        // Tokenize the string key=value
        //key = strtok(line, sep);

        printf("Received value for %s: %s\n", key, value);
    }

    fclose(cfg);

    return 0;
}

